package com.zzyl.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.aliyun.iot20180120.Client;
import com.aliyun.iot20180120.models.QueryDevicePropertiesDataRequest;
import com.aliyun.iot20180120.models.QueryDevicePropertiesDataResponse;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zzyl.base.PageBean;
import com.zzyl.constant.Constants;
import com.zzyl.constant.WeChatConstants;
import com.zzyl.dto.DeviceDto;
import com.zzyl.dto.UserLoginRequestDto;
import com.zzyl.entity.Member;
import com.zzyl.mapper.DeviceDataMapper;
import com.zzyl.mapper.DeviceMapper;
import com.zzyl.mapper.MemberMapper;
import com.zzyl.properties.AliyunIotProperties;
import com.zzyl.properties.JwtTokenProperties;
import com.zzyl.properties.WeChatProperties;
import com.zzyl.service.*;
import com.zzyl.utils.JwtUtil;
import com.zzyl.vo.*;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service
public class MemberServiceImpl implements MemberService {

    private static final List<String> DEFAULT_NICKNAME_PREFIX =
            List.of("生活更美好", "大桔大利", "日富一日", "好柿开花", "柿柿如意", "一椰暴富", "大柚所为", "杨梅吐气", "天生荔枝");

    @Autowired
    private MemberMapper memberMapper;
    @Autowired
    private ContractService contractService;
    @Autowired
    private MemberElderService memberElderService;
    @Autowired
    private OrderService orderService;

    @Autowired
    private JwtTokenProperties jwtTokenProperties;
    @Autowired
    private WeChatProperties weChatProperties;

    @Autowired
    private WechatService wechatService;

    @Autowired
    private DeviceMapper deviceMapper;

    /**
     * 根据id查询用户
     *
     * @param id 用户id
     * @return 用户信息
     */
    @Override
    public Member getById(Long id) {
        return memberMapper.selectById(id);
    }

    /**
     * 分页查询用户列表
     *
     * @param page     当前页码
     * @param pageSize 每页数量
     * @param phone    手机号
     * @param nickname 昵称
     * @return 分页结果
     */
    @Override
    public PageBean<MemberVo> page(Integer page, Integer pageSize, String phone, String nickname) {
        PageHelper.startPage(page, pageSize);
        Page<Member> listPage = memberMapper.page(phone, nickname);

        PageBean<MemberVo> pageBean = PageBean.of(listPage, MemberVo.class);

        pageBean.getRecords().forEach(memberVo -> {
            List<ContractVo> contractVos = contractService.listByMemberPhone(memberVo.getPhone());
            memberVo.setIsSign(contractVos.isEmpty() ? "否" : "是");
            List<OrderVo> orderVos = orderService.listByMemberId(memberVo.getId());
            memberVo.setOrderCount(orderVos.size());
            List<MemberElderVo> memberElderVos = memberElderService.listByMemberId(memberVo.getId());
            List<String> collect = memberElderVos.stream().map(m -> m.getElderVo().getName()).collect(Collectors.toList());
            memberVo.setElderNames(String.join(",", collect));
        });
        return pageBean;
    }

    /**
     * wx登录
     *
     * @param dto 用户登录请求Dto
     * @return {@code ResponseResult }
     * @author YiSheep
     */
    @Override
    @Transactional
    public WxLoginVo wxLogin(UserLoginRequestDto dto) {
        String openid = wechatService.getOpenid(dto.getCode());
        String phone = wechatService.getPhone(dto.getPhoneCode());
        //判断member表中是否存在openId，其实就是更加openId查询，肯定只能查到1条数据
        //查到了，就不用管，如果查询不到就添加一条新数据（主键自增返回）
        //随机生成一个nickName，从上面的集合DEFAULT_NICKNAME_PREFIX中获取
        Member member = memberMapper.getByOpenId(openid);
        if (ObjectUtil.isEmpty(member)) {
            member = Member.builder().openId(openid).build();//设置openId
            String nickName = RandomUtil.randomEle(DEFAULT_NICKNAME_PREFIX) + RandomUtil.randomNumbers(4);
            member.setName(nickName);//设置昵称
            member.setPhone(phone);//设置手机号
            memberMapper.save(member);
        }
        //根据id生成jwt，将jwt、nickName封装到Vo中返回
        Map<String, Object> claims = new HashMap<>();
        claims.put("id", member.getId());
        String jwt = JwtUtil.createJWT(jwtTokenProperties.getSecretKey(), jwtTokenProperties.getTtl(), claims);
        return WxLoginVo.builder().nickName(member.getName()).token(jwt).build();

        /*//1、根据dto中的code，去调用微信的小程序登录接口（携带4个参数），Hutool发送
        Map<String, Object> map = Map.of(
                "appid", weChatProperties.getAppid(),
                "secret", weChatProperties.getSecret(),
                "js_code", dto.getCode());
        String result = HttpUtil.get(WeChatConstants.WX_LOGIN_URL, map);
        JSONObject jsonObject = JSONUtil.parseObj(result);
        String openid = jsonObject.getStr("openid");
        if (StringUtils.isBlank(openid)) {
            throw new RuntimeException(jsonObject.getStr("errmsg"));
        }
        //获取token
        Map<String, Object> tokenMap = Map.of(
                "appid", weChatProperties.getAppid(),
                "secret", weChatProperties.getSecret());
        String tokenResult = HttpUtil.get(WeChatConstants.WX_TOKEN_URL, tokenMap);
        JSONObject parsedObj = JSONUtil.parseObj(tokenResult);
        String token = parsedObj.getStr("access_token");
        if (StringUtils.isBlank(token)) {
            throw new RuntimeException(jsonObject.getStr("errmsg"));
        }
        //根据 token 获取手机号
        Map<String, Object> phoneMap = Map.of(
                "code", dto.getPhoneCode()
        );
        //注意post请求用json
        String post = HttpUtil.post(WeChatConstants.WX_PHONE_URL+token, JSONUtil.toJsonStr(phoneMap));
        JSONObject object = JSONUtil.parseObj(post);
        String phone = object.getJSONObject("phone_info").getStr("phoneNumber");
        //2、判断member表中是否存在openId，其实就是更加openId查询，肯定只能查到1条数据
        //3、查到了，就不用管，如果查询不到就添加一条新数据（主键自增返回）
        //4、随机生成一个nickName，从上面的集合DEFAULT_NICKNAME_PREFIX中获取
        Member member = memberMapper.getByOpenId(openid);
        if (ObjectUtil.isEmpty(member)) {
            member = Member.builder().openId(openid).build();
            String nickName = RandomUtil.randomEle(DEFAULT_NICKNAME_PREFIX) + RandomUtil.randomNumbers(4);
            member.setName(nickName);//设置昵称
            member.setPhone(phone);
            memberMapper.save(member);
        }
        //5、根据id生成jwt，将jwt、nickName封装到Vo中返回
        Map<String, Object> claims = new HashMap<>();
        claims.put("id", member.getId());
        String jwt = JwtUtil.createJWT(jwtTokenProperties.getSecretKey(), jwtTokenProperties.getTtl(), claims);

        return WxLoginVo.builder().nickName(member.getName()).token(jwt).build();*/
    }

}
